package com.example.demo.util;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 */
public class RestTemplateUtil {

    public static String sendPost(RestTemplate restTemplate, String url, String jsonBody)
    {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonBody, headers);
        return restTemplate.postForObject(url, formEntity, String.class);
    }


    public static String sendGet(RestTemplate restTemplate, String url)
    {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * RestTemplate发送POST请求之formData形式
     * @return String
     */
    public static String sendPostFormData(RestTemplate restTemplate, String url, MultiValueMap<String, Object> map)
    {
        HttpHeaders headers = new HttpHeaders();
        //头部类型
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //构造实体对象
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
        //发起请求,服务地址，请求参数，返回消息体的数据类型
        //body
        String body = restTemplate.postForObject(url, param, String.class);
        return body;
    }

    public static <T> ResponseEntity<T> sendPostForEntity(RestTemplate restTemplate, String url, Object req , Class<T> res)
    {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<Object> formEntity = new HttpEntity<>(req, headers);
        return restTemplate.postForEntity(url, formEntity, res);
    }

}
